var _map;
var _latlng = new google.maps.LatLng(52.299871,5.236015);
var _userLocationMarker;
var _accuracyCircle = new google.maps.Circle({
  fillColor: '#0000ff',
  fillOpacity: 0.1,
  strokeColor: '#0000ff',
  strokeOpacity: 0.3,
  strokeWeight: 1
});
//Layers
var _pathLayer;
var _flickrLayer;
var _panoramioLayer;
var _panoramioTagLayer;
//Layers state
var _pathLayerEnabled = false;
var _flickrLayerEnabled = false;
var _panoramioLayerEnabled = false;
var _panoramioTagLayerEnabled = false;
var _add_log_message_form = '';
var _re_for_date = /^([1-3][0-9]{3,3})-(0?[1-9]|1[0-2])-(0?[1-9]|[1-2][1-9]|3[0-1])\s([0-1][0-9]|2[0-4]):([0-5][0-9]):([0-5][0-9])$/; 
var _open_info_window;
var _log_message_icon;
var _flickr_id = '322338@N20';
var _panoramio_id = '6028050';

$(document).ready(function() {
    initialize();
    $('#ckb_layer_panoramio').click(Toggle_Panoramio_Layer);
    $('#ckb_layer_panoramio_tag').click(Toggle_Panoramio_Tag_Layer);
    $('#ckb_layer_flickr').click(Toggle_Flickr_Layer);
    $('#ckb_layer_path').click(Toggle_Path_Layer);
    $('#btn_open_login').click(function () {$('#login').dialog('open');});
    $('#btn_home').click(function () {_map.setCenter(_latlng)});
    $('#btn_to_user_position').click(getUsersLocation);
    $('#btn_add_log_message').click(ToggleAddNewLogMessage);
    
    var icon = new google.maps.MarkerImage('static/images/my-location.png',
  new google.maps.Size(14, 14), // Image Size
  new google.maps.Point(0, 0), // Origin
  new google.maps.Point(7, 7)); // Anchor
  _userLocationMarker = new google.maps.Marker({icon: icon});
  _accuracyCircle.bindTo('center', _userLocationMarker, 'position');
  
  _log_message_icon = new google.maps.MarkerImage('static/images/log-icon.png',
  new google.maps.Size(50, 65), // Image Size
  new google.maps.Point(0, 0), // Origin
  new google.maps.Point(50, 50)); // Anchor

});

$(window).load(function(){  
});  

function initialize() {   
    var myOptions = {
      zoom: 10,
      center: _latlng,
      mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    
    //Create the Google map on the given div
    _map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
    //Add_Map_Control("Login", "Click here to open the login screen", "open_login_dialog");
    
    _add_log_message_form = $('#add_log_message_form').html();
    $('#add_log_message_form').html('');
    
}

function Add_Map_Control(label, tooltip, action){
    var div_control = document.createElement('input');
    $(div_control).addClass("map_control");
    $(div_control).val(label);
    $(div_control).attr('title', tooltip);
    $(div_control).attr('type', 'button');
    switch(action){
        case "open_login_dialog":
            $(div_control).click(function () {$('#login').dialog('open');});
            break;
        default:
            $(div_control).click(function () {alert('The given action does not exist');});
            break;
    }
    _map.controls[google.maps.ControlPosition.TOP_RIGHT].push(div_control);
}

function Toggle_Path_Layer(){
    if(!_pathLayerEnabled){
            _pathLayer = new google.maps.KmlLayer('http://html.wuzzon.nl/GPSKitData.kml');
            _pathLayer.setMap(_map);
            _pathLayerEnabled = true;
    }
    else {_pathLayer.setMap(null);_pathLayerEnabled = false;}
}

function Toggle_Flickr_Layer(){
    if(!_flickrLayerEnabled){
    //_flickrLayer = new google.maps.KmlLayer('http://api.flickr.com/services/feeds/geo/?g='+ _flickr_id +'&lang=en-us&format=feed-georss');
    _flickrLayer = new google.maps.KmlLayer('http://api.flickr.com/services/feeds/geo/?id='+ _flickr_id +'&lang=en-us&format=feed-georss');
    _flickrLayer.setMap(_map);
    _flickrLayerEnabled = true;
    }
    else {_flickrLayer.setMap(null);_flickrLayerEnabled = false;}
}

function Toggle_Panoramio_Layer(){
    if(!_panoramioLayerEnabled)
    {
            _panoramioLayer = new google.maps.panoramio.PanoramioLayer();
            //Filter by user id
            _panoramioLayer.setUserId(_panoramio_id);
            _panoramioLayer.setMap(_map);
            _panoramioLayerEnabled = true;
    }
    else {_panoramioLayer.setMap(null);_panoramioLayerEnabled = false;}
}

function Toggle_Panoramio_Tag_Layer(){
    if(!_panoramioTagLayerEnabled)
    {
            _panoramioTagLayer = new google.maps.panoramio.PanoramioLayer();
            //Filter by tag
            _panoramioTagLayer.setTag($('#txt_paoramio_tag').val());
            _panoramioTagLayer.setMap(_map);
            _panoramioTagLayerEnabled = true;
    }
    else {_panoramioTagLayer.setMap(null);_panoramioTagLayerEnabled = false;}
}

function getUsersLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = new google.maps.LatLng(position.coords.latitude,
        position.coords.longitude);
      _map.panTo(pos);
      _userLocationMarker.setPosition(pos);
      _userLocationMarker.setMap(_map);
      _accuracyCircle.setRadius(position.coords.accuracy);
      _accuracyCircle.setMap(_map);
    }, function() {
      // Can find the users location
    });
  }
}

function ToggleAddNewLogMessage() {
$('#btn_add_log_message').addClass('ui-state-hover');
  google.maps.event.addListener(_map, 'click', function(mouseEvent) {
    Add_New_Log_Message('Add log message', _add_log_message_form, mouseEvent.latLng);
  });
}

function Add_New_Log_Message(title, content, latlng){
    $('#btn_add_log_message').removeClass('ui-state-hover');
    var infowindow = new google.maps.InfoWindow({content: content, height:500});

    var marker = new google.maps.Marker({
        position: latlng,
        map: _map,
        title: title
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(_map, marker);
    });
    infowindow.open(_map, marker);
    
    var geocoder = new google.maps.Geocoder();
    var request = {latLng: marker.getPosition()};
    geocoder.geocode(request, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var address = results[0].formatted_address;
          $('#txt_address').val(address);
        }
        else $('#txt_address').val('');
        google.maps.event.clearListeners(_map, 'click');
        $('#txt_lat').val(latlng.lat());
        $('#txt_lng').val(latlng.lng());
        $('#btn_save_log_message').click(function () {Save_Log_Message(infowindow, marker); });
    });
}

function Save_Log_Message(infowindow, marker){
    var error_message = '';
    if($('#txt_title').val() == '') error_message += '<li>You have not entered a "Title"';
    if($('#txt_date').val() == '') error_message += '<li>You have not entered a "Date"';
    else if(!_re_for_date.test($('#txt_date').val()))   error_message += '<li>You have not entered a valid "Date" (yyyy-mm-dd hh:mm:ss)';
    if($('#txt_message').val() == '') error_message += '<li>You have not entered a "Message"';
    if($('#txt_address').val() == '') error_message += '<li>You have not entered a "Address"';
    if($('#txt_lat').val() == '') error_message += '<li>You have not entered a "Lat"';
    if($('#txt_lng').val() == '') error_message += '<li>You have not entered a "Lng"';

    if(error_message == ''){
        $('#form_message').css('display', 'none');
        $.ajax({
            type: "POST",
            url: "php/controller/add_log_message.php",
            data:$('#frm_add_log_message').serialize(),
            success: function(data){
                if(data == 1){
                    content = Create_Log_Message($('#txt_title').val(), $('#txt_message').val(), $('#txt_date').val());
                    Add_Info_Window($('#txt_title').val(), content, marker.getPosition());
                    infowindow.close();
                    marker.setMap(null);
                }
            }
        });    
    }
    else{
        $('#form_message').attr('class', 'form_message_error');
        $('#form_message').html('<ul>' + error_message + "</ul>");
        $('#form_message').css('display', 'block');
    }    
}

function Add_Info_Window(title, content, latlng){
    var infowindow = new google.maps.InfoWindow({content: content});
    var marker = new google.maps.Marker({
        position: latlng,
        map: _map,
        title: title,
        icon: _log_message_icon
    });

    google.maps.event.addListener(marker, 'click', function() {
        if (_open_info_window != null) _open_info_window.close();
        infowindow.open(_map, marker);
        _open_info_window = infowindow;
    });

}

function Create_Log_Message(title, message, log_date){
    var html = '<div class="log_message_header"><div class="log_message_title">'+ title +'</div><div class="log_message_log_date">'+ log_date +'</div></div>';
    html += '<div class="log_message_body">'+ message +'</div>';
    return html;
}


